﻿using Models;
using Scheduledscheduling.Models.TaskOptionsShow;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Scheduledscheduling
{
    public partial class Modify : Form
    {
        TaskOptions op = null;
        public Modify(TaskOptions op)
        {
            this.op = op;
            InitializeComponent();
            StartPosition = FormStartPosition.CenterParent;
            this.label7.Visible = false;
            this.Txt_Token.Visible = false;
            this.label8.Visible = false;
            this.Txt_Data.Visible = false;
            ReadData(this.op);
        }
        private void ReadData(TaskOptions op)
        {
            if (op != null)
            {
                textBox1.Text = op.TaskName;
                textBox2.Text = op.GroupName;
                textBox3.Text = op.Interval.ToString();
                comboBox1.Text = op.RequestType;
                textBox4.Text = op.ApiUrl;
                textBox5.Text = op.Describe;
                textBox1.Enabled = false;
                textBox2.Enabled = false;
                Txt_Token.Text = op.AuthKey;
                Txt_Data.Text = op.AuthValue;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 1. 获取表单数据
            var token = string.Empty;
            var data = string.Empty;
            var selectedValue = comboBox1.SelectedItem?.ToString();

            if (selectedValue == "POST")
            {
                token = Txt_Token.Text.Trim();
                data = Txt_Data.Text.Trim();
            }

            // 2. 校验输入
            if (string.IsNullOrWhiteSpace(textBox1.Text))
            {
                MessageBox.Show("作业名称不能为空");
                return;
            }
            if (string.IsNullOrWhiteSpace(textBox2.Text))
            {
                MessageBox.Show("分组不能为空");
                return;
            }
            if (!int.TryParse(textBox3.Text, out int interval))
            {
                MessageBox.Show($"【{label3.Text}】请输入有效的数字!");
                return;
            }
            if (string.IsNullOrWhiteSpace(comboBox1.Text))
            {
                MessageBox.Show("访问方式不能为空");
                return;
            }
            if (string.IsNullOrWhiteSpace(textBox4.Text))
            {
                MessageBox.Show("调度地址不能为空");
                return;
            }

            // 3. 新增或修改
            bool isNew = op == null;
            if (isNew)
            {
                var newOp = new TaskOptions
                {
                    TaskName = textBox1.Text.Trim(),
                    GroupName = textBox2.Text.Trim(),
                    Interval = interval,
                    ApiUrl = textBox4.Text.Trim(),
                    Describe = textBox5.Text.Trim(),
                    RequestType = selectedValue,
                    Status = (int)Models.TaskOptionsShow.Status.Working,
                    AuthKey = selectedValue == "POST" ? token : null,
                    AuthValue = selectedValue == "POST" ? data : null
                };

                if (!QueryRepeat(newOp))
                {
                    MessageBox.Show($"数据库上已经有【{newOp.TaskName}】和【{newOp.GroupName}】的数据了，请不要重复添加");
                    return;
                }

                try
                {
                    button1.Enabled = false;
                    var id = Sugar.db.Insertable(newOp).ExecuteReturnIdentity();
                    if (id > 0)
                    {
                        var mo = Sugar.db.Queryable<TaskOptions>().Where(it => it.Id == id).First();
                        if (mo != null)
                        {
                            var om = new TaskOptionsShow
                            {
                                Id = mo.Id,
                                TaskName = mo.TaskName,
                                GroupName = mo.GroupName,
                                Interval = mo.Interval,
                                ApiUrl = mo.ApiUrl,
                                RequestType = mo.RequestType,
                                Status = mo.Status,
                                StatusDesc = "待运行",
                                Describe = mo.Describe,
                                AuthKey = mo.RequestType == "POST" ? token : null,
                                AuthValue = mo.RequestType == "POST" ? data : null
                            };
                            Main.timers.Add(om);
                        }
                    }
                    else
                    {
                        MessageBox.Show("添加失败");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
            else
            {
                // 修改
                op.TaskName = textBox1.Text.Trim();
                op.GroupName = textBox2.Text.Trim();
                op.Interval = interval;
                op.ApiUrl = textBox4.Text.Trim();
                op.Describe = textBox5.Text.Trim();
                op.RequestType = selectedValue;
                op.AuthKey = selectedValue == "POST" ? token : null;
                op.AuthValue = selectedValue == "POST" ? data : null;
                op.Status = (int)Models.TaskOptionsShow.Status.Working;

                try
                {
                    if (Sugar.db.GetSimpleClient<TaskOptions>().Update(op))
                    {
                        for (int i = 0; i < Main.timers.Count; i++)
                        {
                            if (Main.timers[i].TaskName == op.TaskName && Main.timers[i].GroupName == op.GroupName && Main.timers[i].Id == op.Id)
                            {
                                Main.timers[i].Status = op.Status;
                                Main.timers[i].Interval = op.Interval;
                                Main.timers[i].ApiUrl = op.ApiUrl;
                                Main.timers[i].RequestType = op.RequestType;
                                Main.timers[i].Describe = op.Describe;
                                if (op.RequestType == "POST")
                                {
                                    Main.timers[i].AuthKey = token;
                                    Main.timers[i].AuthValue = data;
                                }
                                else
                                {
                                    Main.timers[i].AuthKey = null;
                                    Main.timers[i].AuthValue = null;
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("修改失败");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
            this.Close();
        }

        private bool QueryRepeat(TaskOptions op)
        {
            var result = false;
            var lst = Sugar.db.Queryable<TaskOptions>().Where(o => o.TaskName == op.TaskName || o.GroupName == op.GroupName).ToList();
            if (lst.Any())
            {
                result = false;
            }
            else
            {
                result = true;
            }
            return result;
        }

        private void Modify_Load(object sender, EventArgs e)
        {
            if (op == null)
            {
                groupBox1.Text = "添加";
            }
            else
            {
                groupBox1.Text = "修改";
            }
            this.Text = groupBox1.Text;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectedValue = comboBox1.SelectedItem?.ToString();
            switch (selectedValue)
            {
                case "GET":
                    this.label7.Visible = false;
                    this.Txt_Token.Visible = false;
                    this.label8.Visible = false;
                    this.Txt_Data.Visible = false;
                    break;
                    case "POST":
                    this.label7.Visible = true;
                    this.Txt_Token.Visible = true;
                    this.label8.Visible = true;
                    this.Txt_Data.Visible = true;
                    break;
            }

        }
    }
}
